package com.jbh.wanandroidkotlin.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.jbh.apilibrary.AppData
import com.jbh.apilibrary.bean.IndexArticleListBean
import com.jbh.apilibrary.bean.IndexArticleListResult
import com.jbh.apilibrary.i.ApiCallBack
import com.jbh.wanandroidkotlin.R
import com.jbh.wanandroidkotlin.activity.CommonActivity
import com.jbh.wanandroidkotlin.util.WEB_LINK
import com.jbh.wanandroidkotlin.util.data
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener
import com.scwang.smartrefresh.layout.listener.OnRefreshListener
import kotlinx.android.synthetic.main.common_list_layout.*

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

class WDFragment : Fragment() {

    private var param1: String? = null
    private var param2: String? = null

    /**
     * 记录上拉还是下拉
     */
    private var isPullRefresh = true
    /**
     * 当前页码
     */
    private var page = 0
    /**
     * 文章的总页数
     *
     */
    private var pageAll = 0;

    private var contentListAdapter:ContentListAdapter?=null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_w_d, container, false)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: String ="", param2: String="") =
            WDFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }


    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mSmartRefreshLayout?.apply {
            autoRefresh()
            setEnableRefresh(true)
            setEnableLoadMore(true)
            setOnRefreshListener(RefreshHead())
            setOnLoadMoreListener(RefreshFoot())
        }

        mRecyclerView.apply {
            val l = LinearLayoutManager(activity)
            l.orientation = LinearLayoutManager.VERTICAL
            layoutManager = l
            contentListAdapter = ContentListAdapter(listContent)
            adapter = contentListAdapter
        }


        contentListAdapter?.setOnItemClickListener { adapter, view, position ->
            val b = Bundle();
            b.putString(WEB_LINK,listContent[position].link)
            startActivity(Intent(activity, CommonActivity::class.java).putExtra(data, b))
        }

    }


    inner class RefreshFoot : OnLoadMoreListener {

        override fun onLoadMore(refreshLayout: RefreshLayout) {
            isPullRefresh = false
            page ++ ;
            if (pageAll >= page){
                wenDaTask()
            }else{
                mSmartRefreshLayout?.finishLoadMore(0, true, true)
            }
        }
    }


    inner class RefreshHead : OnRefreshListener {

        override fun onRefresh(refreshLayout: RefreshLayout) {
            isPullRefresh = true
            page = 0;
            listContent.clear()
            wenDaTask()
        }
    }




    inner class ContentListAdapter(l : List<IndexArticleListBean>) :
        BaseQuickAdapter<IndexArticleListBean, BaseViewHolder>(R.layout.item_index_layout,l){
        override fun convert(helper: BaseViewHolder, item: IndexArticleListBean) {
            helper.setText(R.id.title,item.title)
                .setText(R.id.tv_subtitle,item.shareUser)
        }
    }



    private var  listContent= mutableListOf<IndexArticleListBean>()

    /**
     * 问答
     */
    private fun wenDaTask(){
        AppData.instance().wenDaTask(page,object :ApiCallBack<IndexArticleListResult>{
            override fun success(data: IndexArticleListResult) {
                println("[wenDaTask] - > success = ${Gson().toJson(data)}")
                activity?.runOnUiThread {
                    pageAll = data.pageCount
                    println("[indexArticleTask] - > success = $pageAll")
                    listContent.addAll(data.datas)
                    contentListAdapter ?.notifyDataSetChanged()
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, false)
                    }
                }
            }

            override fun error(error: String) {
                println("[wenDaTask] - > error = $error")
                activity?.runOnUiThread {
                    if (isPullRefresh) {
                        mSmartRefreshLayout?.finishRefresh()
                    } else {
                        mSmartRefreshLayout?.finishLoadMore(0, true, true)
                    }
                }
            }
        })
    }

}